var prefs = new gadgets.Prefs();
var maxValue = 500;
var now = new Date();
//alert(now);
var lastMonth = new Date();
lastMonth.setTime(now.getTime() - (30 * 24 * 60 * 60000));
//alert(lastMonth);
// Load the Google data JavaScript client library.
google.load('gdata', '1.x', {
    packages: ['analytics']
});

// Set the callback function when the library is ready.
google.setOnLoadCallback(init);

simpleEncoding =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

//encode chart data into simple form
function simpleEncode(valueArray, maxValue) {

    var chartData = ['s:'];
    for (var i = 0; i < valueArray.length; i++) {
        var currentValue = valueArray[i];
        if (!isNaN(currentValue) && currentValue >= 0) {
            chartData.push(simpleEncoding.charAt(Math.round((simpleEncoding.length - 1) *
            currentValue / maxValue)));
        }
        else {
            chartData.push('_');
        }
    }
    return chartData.join('');
}

function formatDate(date) {
    result = date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate());
    //alert(date+'->'+result);
    return result;

}
function pad(date) {
    result = '' + date;
    if (result.length == 1) {
        result = '0' + result;
    }
    return result;
}

/**
 * Main method to get report data from the Export API.
 */
function getDataFeed() {

    var myFeedUri = 'https://www.google.com/analytics/feeds/data' +
    '?end-date=' + formatDate(now) +
    '&start-date=' + formatDate(lastMonth) +
    '&dimensions=ga:date' +
    '&metrics=ga:visits,ga:pageviews' +
    '&sort=ga:date' +
    '&ids=' + prefs.getString("tableID");
    //  alert(myFeedUri);
    myService.getDataFeed(myFeedUri, handleDataFeed, handleError);
}


/**
 * This is called once the Google Data JavaScript library has been loaded.
 * It creates a new AnalyticsService object, adds a click handler to the
 * authentication button and updates the button text depending on the status.
 */
function init() {
    myService = new google.gdata.analytics.AnalyticsService('gaExportAPI_acctSample_v1.0');
    scope = 'https://www.google.com/analytics/feeds';
    var button = document.getElementById('authButton');

    // Add a click handler to the Authentication button.
    button.onclick = function() {
        // Test if the user is not authenticated.
        if (!google.accounts.user.checkLogin(scope)) {
            // Authenticate the user.
            google.accounts.user.login(scope);
        } else {
            // Log the user out.
            google.accounts.user.logout();
            getStatus();
        }
    }
    getStatus();
    getDataFeed();
}

/**
 * Utility method to display the user controls if the user is 
 * logged in. If user is logged in, get Account data and
 * get Report Data buttons are displayed.
 */
function getStatus() {
    var getAccountButton = document.getElementById('getAccount');
    getAccountButton.onclick = getAccountFeed;

    var dataControls = document.getElementById('dataControls');
    var loginButton = document.getElementById('authButton');
    if (!google.accounts.user.checkLogin(scope)) {
        dataControls.style.display = 'none';
        // hide control div
        loginButton.innerHTML = 'Access Google Analytics';
    } else {
        dataControls.style.display = 'block';
        // show control div
        loginButton.innerHTML = 'Logout';
    }
}




/**
 * Handle the data returned by the Export API by constructing the 
 * inner parts of an HTML table and inserting into the HTML File.
 * @param {object} result Parameter passed back from the feed handler.
 */
function handleDataFeed(result) {

    // An array of Analytics feed entries.
    var entries = result.feed.getEntries();
    var chartValues = new Array();
    var chartDates = new Array();

    // Create an HTML Table using an array of elements.
    var outputTable = ['<table><tr>',
    '<th>Date</th>',
    '<th>Page Visits</th>',
    '<th>Pageviews</th></tr>'];

    // Iterate through the feed entries and add the data as table rows.
    for (var i = 0, entry; entry = entries[i]; ++i) {
        chartValues[i] = entry.getValueOf('ga:visits');
        chartDates[i] = entry.getValueOf('ga:date');
        //adjust the max value
        maxValue = Math.max(maxValue, chartValues[i]);
        // Add a row in the HTML Table array.
        var row = [
        entry.getValueOf('ga:date'),
        entry.getValueOf('ga:visits'),
        entry.getValueOf('ga:pageviews')
        ].join('</td><td>');
        outputTable.push('<tr><td>', row, '</td></tr>');
    }
    outputTable.push('</table>');
    // Insert the chart into the UI.
    document.getElementById('outputDiv').innerHTML =
    outputTable.join('');
    values = simpleEncode(chartValues, maxValue);
    url = 'http://chart.apis.google.com/chart?cht=lc&chs=350x200&chd=' + values +
    '&chtt=Site+Visits+per+Day|30+days' +
    '&chxt=x,y' +
    '&chxl=0:|' + formatDate(lastMonth) + '|' + formatDate(now) + '|' +
    '1:|0|' + maxValue;
    //  alert(url);
    document.getElementById('chartDiv').innerHTML = '<img src="' + url + '"/>';

}

/**
 * Alert any errors that come from the API request.
 * @param {object} e The error object returned by the Analytics API.
 */
function handleError(e) {
    var error = 'There was an error!\n';
    if (e.cause) {
        error += e.cause.status;
    } else {
        error.message;
    }
    alert(error);
}
/**
 * Main method to get account data from the API.
 */
function getAccountFeed() {
    var myFeedUri =
    'https://www.google.com/analytics/feeds/accounts/default?max-results=50';
    myService.getAccountFeed(myFeedUri, handleAccountFeed, handleError);
}

/**
 * Handle the account data returned by the Export API by constructing the inner parts
 * of an HTML table and inserting into the HTML file.
 * @param {object} result Parameter passed back from the feed handler.
 */
function handleAccountFeed(result) {
    // An array of analytics feed entries.
    var entries = result.feed.getEntries();
    // Create an HTML Table using an array of elements.
    var outputTable = ['<table><tr>',
    '<th>Account Name</th>',
    '<th>Profile Name</th>',
    '<th>Profile ID</th>',
    '<th>Table Id</th></tr>'];

    // Iterate through the feed entries and add the data as table rows.
    for (var i = 0, entry; entry = entries[i]; ++i) {
        // Add a row in the HTML Table array for each value.
        var row = [
        entry.getPropertyValue('ga:AccountName'),
        entry.getTitle().getText(),
        entry.getPropertyValue('ga:ProfileId'),
        entry.getTableId().getValue()
        ].join('</td><td>');
        outputTable.push('<tr><td>', row, '</td></tr>');
    }
    outputTable.push('</table>');

    // Insert the table into the UI.
    document.getElementById('outputDiv').innerHTML =
    outputTable.join('');
}
